import { HubConnection, HubConnectionBuilder, LogLevel } from '@microsoft/signalr';

export class SignalRService {
  private hubConnection: HubConnection | null = null;
  private isConnected = false;

  // 连接状态
  public get connectionState() {
    return this.isConnected;
  }

  // 建立连接
  public async startConnection(): Promise<void> {
    try {
      this.hubConnection = new HubConnectionBuilder()
        .withUrl('/hubs/enterout', {
          skipNegotiation: true,
          transport: 1 // WebSockets only
        })
        .configureLogging(LogLevel.Information)
        .withAutomaticReconnect()
        .build();

      // 监听连接状态
      this.hubConnection.onreconnecting(() => {
        console.log('SignalR 正在重新连接...');
        this.isConnected = false;
      });

      this.hubConnection.onreconnected(() => {
        console.log('SignalR 重新连接成功');
        this.isConnected = true;
      });

      this.hubConnection.onclose(() => {
        console.log('SignalR 连接已关闭');
        this.isConnected = false;
      });

      await this.hubConnection.start();
      this.isConnected = true;
      console.log('SignalR 连接成功');
    } catch (error) {
      console.error('SignalR 连接失败:', error);
      throw error;
    }
  }

  // 停止连接
  public async stopConnection(): Promise<void> {
    if (this.hubConnection) {
      await this.hubConnection.stop();
      this.hubConnection = null;
      this.isConnected = false;
      console.log('SignalR 连接已停止');
    }
  }

  // 监听调拨明细数据
  public onXiangQings(callback: (data: any[]) => void): void {
    if (this.hubConnection) {
      this.hubConnection.on('XiangQings', (data) => {
        console.log('收到调拨明细数据:', data);
        callback(data);
      });
    }
  }

  // 移除监听器
  public offXiangQings(): void {
    if (this.hubConnection) {
      this.hubConnection.off('XiangQings');
    }
  }

  // 手动触发数据推送
  public async triggerPush(): Promise<void> {
    try {
      const response = await fetch('/api/Hub/Push', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        }
      });
      const result = await response.text();
      console.log('手动推送结果:', result);
    } catch (error) {
      console.error('手动推送失败:', error);
    }
  }
}

// 创建单例实例
export const signalRService = new SignalRService(); 